import { useAtom } from 'jotai';
import React, { useCallback } from 'react';
import type { DropTargetMonitor } from 'react-dnd';
import { useDrop } from 'react-dnd';
import { useAtomCallback } from 'jotai/utils';
import { AllComponents, leftDatas } from '../datas';
import { comDataAtom, demoAtom } from '../models';
import styles from './index.module.less';
// import Editor from './Editor';

const Context = () => {
  const [comData, setComData] = useAtom(comDataAtom);
  const [demo, setDemo] = useAtom(demoAtom);

  const [{ isOver, draggingColor, canDrop }, drop] = useDrop(
    () => ({
      accept: leftDatas.map((item) => item.type),
      // 接收拖拽至容器后的数据
      drop(_item, monitor) {
        updata(_item);
        return undefined;
      },
      collect: (monitor: DropTargetMonitor) => ({
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
        draggingColor: monitor.getItemType() as string,
      }),
    }),
    [],
  );

  const updata = useAtomCallback(
    useCallback(
      (get, _set, _item: any) => {
        const newComData = get(comDataAtom);
        console.log('_item', _item);

        newComData?.push(_item);
        setComData(newComData);
        return newComData;
      },
      [setComData, comDataAtom],
    ),
  );

  const onClickWrap = (itemData) => {
    setDemo({
      isEditor: true,
    });
  };

  return (
    <>
      <div ref={drop} className={styles.context}>
        {comData?.length === 0 && <p>拖拽组件到此区域.</p>}
        {/* 动态渲染组件 */}
        {comData?.map?.((item, i) => {
          const Com = AllComponents[item.type];
          return (
            <div key={`${item.type + i}`} onClick={() => onClickWrap(item)}>
              <Com {...item} />
            </div>
          );
        })}
        {/* <Editor /> */}
      </div>
    </>
  );
};

export default Context;
